package org.example.config;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import lombok.extern.slf4j.Slf4j;
import org.example.listener.EventListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author zhangjg
 * @desc
 * @date 2023/05/07 17:14
 **/
@Component
@Slf4j
public class SocketioServerConfig implements InitializingBean {

    @Value("${push.server.port}")
    private int serverPort;

    @Value("${push.server.host}")
    private String serverHost;

    @Autowired
    private EventListener eventListener;

    @Autowired
    private SocketIOServer socketIOServer;

    @Override
    public void afterPropertiesSet() throws Exception {
        socketIOServer.start();
        log.info("socketIOServer start");
    }

    @Bean
    public SocketIOServer socketIOServer() {
        Configuration config = new Configuration();
        config.setPort(serverPort);
        config.setHostname(serverHost);
        config.setWorkerThreads(24);
        config.setBossThreads(2);
//        config.setContext("/websocket-sockjs");

        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setReuseAddress(true);
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        config.setSocketConfig(socketConfig);

        SocketIOServer server = new SocketIOServer(config);
        server.addListeners(eventListener);
        return server;
    }
}
